package com.nettylern.netty.解码器;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author liliang
 * @date 2019/12/5.
 */
public class EchoClient {

    public void connect(String host, int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap client = new Bootstrap();
        client.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        ByteBuf deLimiter = Unpooled.copiedBuffer("$_".getBytes());
                        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, deLimiter));
                        channel.pipeline().addLast(new StringDecoder());
                        channel.pipeline().addLast(new EchoClientHandler());
                    }
                });
        try {
            ChannelFuture future = client.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 8080;
        new EchoClient().connect("127.0.0.1", port);
    }
}
